package cn.dinkevin.xui.net.converter;

import com.google.gson.JsonSyntaxException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import cn.dinkevin.xui.net.exception.BizException;
import cn.dinkevin.xui.util.LogUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by panda on 2017/5/11 下午11:28.
 */
public class ApiErrorConverterFactory extends Converter.Factory {

    private final Converter.Factory mDelegateFactory;

    public ApiErrorConverterFactory(Converter.Factory delegateFactory) {
        mDelegateFactory = delegateFactory;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return mDelegateFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        Converter<ResponseBody, ?> apiErrorConverter = mDelegateFactory.responseBodyConverter(BizException.class, annotations, retrofit);
        Converter<ResponseBody, ?> delegateConverter = mDelegateFactory.responseBodyConverter(type, annotations, retrofit);

        return value -> {
            MediaType mediaType = value.contentType();
            String stringBody = value.string();
            try {
                Object object = apiErrorConverter.convert(ResponseBody.create(mediaType, stringBody));
                if (object instanceof BizException && ((BizException) object).isBizError()) {
                    LogUtil.format_e("BizException %s",object);
                    throw (BizException) object;
                }
            } catch (JsonSyntaxException ignored) {

            }
            return delegateConverter.convert(ResponseBody.create(mediaType, stringBody));
        };
    }
}
